define(['registry', 'collections/record_list', 'models/record', 'views/form'],

function(app_registry, Records, Record, Form) {

  var AppView = Backbone.View.extend({
    el: '#todoapp',
    statsTemplate: _.template($('#stats-template').html()),

    events: {
      'click #new-todo': 'new',
      'click #clear-completed': 'clearCompleted',
      'click #toggle-all': 'toggleAllComplete'
    },

    initialize: function() {
      this.allCheckbox = this.$('#toggle-all')[0];
      this.$input = this.$('#new-todo');
      this.$footer = this.$('#footer');
      this.$main = this.$('#main');

      // this.collection.on('add', this.addOne);
      this.listenTo(this.collection, 'change:completed', this.filterOne);
      this.listenTo(this.collection, 'filter', this.filterAll);
      this.listenTo(this.collection, 'all', this.render);
      this.listenTo(this.collection, 'remove', this.updateSelectedItem);
      this.listenTo(this.collection, 'change', this.updateSelectedItem);
    },

    updateSelectedItem: function(model) {
      $('#item-detail-view').trigger('update_detail', { id: model.id })
    },

    render: function() {
      var completed = this.collection.completed().length;
      var remaining = this.collection.remaining().length;

      if (this.collection.length) {
        this.$footer.show();

        this.$footer.html(this.statsTemplate({
          completed: completed,
          remaining: remaining
        }));

        this.$('#filters li a')
          .removeClass('selected')
          .filter('[href="#/' + ( app_registry.vars.TodoFilter || '' ) + '"]')
          .addClass('selected');
      } else {
        this.$footer.hide();
      }

      // this.allCheckbox.checked = !remaining;
      return this;
    },

    new: function() {
      new Form({ 
        model: new Record(),
        collection: this.collection
      });
    },

    filterOne: function( todo ) {
      todo.trigger('visible');
    },

    filterAll: function() {
      this.collection.each(this.filterOne, this);
    },

    // Clear all completed todo items, destroying their models.
    clearCompleted: function() {
      _.invoke(this.collection.completed(), 'destroy');
      return false;
    },

    toggleAllComplete: function() {
      var completed = this.allCheckbox.checked;

      this.collection.each(function( todo ) {
        todo.save({
          'completed': completed
        });
      });
    },

  });

  return AppView;
});
